package traitement;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JPanel;

public class TraitementApercu extends JPanel{
	private static final long serialVersionUID = 1L;
	private Image image = null, scaledImage = null;
	double ratio = 0;
	int width,height;
	int currentWidth, currentHeight;
	
	public TraitementApercu(String path) {
		super();
		
		if(path!=null)
			updateSynoptic(path);
		this.setLayout(getLayout());
	}
	
	public void updateSynoptic(String path){
		try {
			image = ImageIO.read(new File(path));
			width = image.getWidth(null);
			height = image.getHeight(null);
		} catch (IOException e) {
			try {
				//image = ImageIO.read(GraphEditor.class
				//		.getResource("/graphEd/images/blank.jpg"));
				//image = ImageIO.read(new File("G:/blank.jpg"));
				image = ImageIO.read(new File("/graphEd/images/blank.jpg"));


			} catch (Exception e1) {
				System.err.println("Exception.");
				//e1.printStackTrace();
			}
			//e.printStackTrace();
		}
		
		
		currentWidth = width;
		currentHeight = height;
		
		ratio = ((double)width)/((double)height);
		
		if (image != null) { // Si l'image existe, ...	
			scaledImage = image;
		}// Sinon afficher une image: "image non disponible"
		this.setPreferredSize(new Dimension(width, height));

		repaint();
	}
	
	
	public void resizeByWidth(){
		currentWidth = (int)(getHeight()*ratio);
		currentHeight = getHeight();
		scaledImage = image.getScaledInstance(currentWidth, currentHeight, Image.SCALE_SMOOTH);
	}
	
	public void resizeByHeight(){
		currentWidth = getWidth();
		currentHeight = (int)(getWidth()/ratio);
		scaledImage = image.getScaledInstance(currentWidth, currentHeight, Image.SCALE_SMOOTH);
	}
	

	public void paint(Graphics g) {
		super.paintComponent(g);

		if (image != null) { // Si l'image existe, ...
			
			if(width > getWidth())
				resizeByHeight();
			if(height > getHeight())
				resizeByWidth();
			//System.out.println("Width:"+scaledImage.getWidth(null)+"\t"+this.getWidth());
			
			g.drawImage(scaledImage, (getWidth()-currentWidth)/2, (getHeight()-currentHeight)/2, this);
			this.setBorder(BorderFactory.createLineBorder(Color.black));

		} else
			System.err.println("Picture not found");
	}

}
